package com.hdcx.Minfresh.adapter;


import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.hdcx.Minfresh.R;
import com.hdcx.Minfresh.activity.DetailActivity;
import com.hdcx.Minfresh.activity.GoodListActivity;
import com.hdcx.Minfresh.activity.MainActivity;
import com.hdcx.Minfresh.bean.IndexWrapper;
import com.hdcx.Minfresh.holder.MainHolder;
import com.hdcx.Minfresh.url.RequstCode;
import com.hdcx.Minfresh.util.AppUtil;
import com.hdcx.Minfresh.view.GlideImageLoader;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerClickListener;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/11/9.
 */

public class MainAdapter extends RecyclerView.Adapter<MainHolder> {
    private FragmentActivity mActivity;
    private List<ImageView> dotList = new ArrayList<>();
    private List<Integer> timeList = new ArrayList<>();
    private int currentIndex;
    private List<TextView> timeTextViewList = new ArrayList<>();
    private Handler timeHandler;
    int Timetemp = 10000;
    IndexWrapper data;
    Boolean tag= false;

    public MainAdapter(FragmentActivity activity) {
        mActivity = activity;
    }

    @Override
    public MainHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater layoutInflater = LayoutInflater.from(mActivity);
        View view;
        if (viewType == 0) {
            view = layoutInflater.inflate(R.layout.item_fragment_main_one, parent, false);
        } else {
            view = layoutInflater.inflate(R.layout.item_fragment_main_two, parent, false);
        }
        return new MainHolder(view, viewType);
    }

    @Override
    public void onBindViewHolder(MainHolder holder, final int position) {
        if (position == 0) {
            Timetemp = data.getData().getXscp().getTime();
            Log.e("MainAdapter", "MainAdapter--onBindViewHolder--"+Timetemp);
            holder.banner.setImageLoader(new GlideImageLoader());
            List<String> list = new ArrayList<>();
            for (int i =0;i<data.getData().getBanner().size();i++){
                list.add(data.getData().getBanner().get(i).getImages());
            }
            for(int i=0;i<data.getData().getSort().size();i++){
                AppUtil.showPic(data.getData().getSort().get(i).getImages(),holder.img_mains[i]);
                final int finalI = i;
                holder.img_mains[i].setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                       MainActivity activity = (MainActivity)mActivity;
                        activity.isFromMainFragmentToClassify=true;
                        activity.id = data.getData().getSort().get(finalI).getId();
                        activity.changeFragment(activity.classify);
                    }
                });
                holder.tv_mains[i].setText(data.getData().getSort().get(i).getName());
            }
            holder.banner.setImages(list);
            holder.banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
            holder.banner.setIndicatorGravity(BannerConfig.CENTER);
            holder.banner.start();
            holder.banner.setOnBannerClickListener(new OnBannerClickListener() {
                @Override
                public void OnBannerClick(int banPos) {
                    Intent intent;
                    if(data.getData().getBanner().get(banPos-1).getType().equals("class")){
                        intent = new Intent(mActivity, GoodListActivity.class);
                        intent.putExtra("id",data.getData().getBanner().get(banPos-1).getValue());
                    }else{
//                        if (AppUtil.need_to_login(mActivity)) {
//                            return;
//                        }
                        intent = new Intent(mActivity, DetailActivity.class);
                        intent.putExtra("id",data.getData().getBanner().get(banPos-1).getValue());
                    }
                    mActivity.startActivity(intent);
                }
            });
            if (Timetemp>0){
                timeTextViewList.add(holder.tv_hour);
                timeTextViewList.add(holder.tv_point);
                timeTextViewList.add(holder.tv_second);
                startRun(Timetemp, 0);
                timeHandler = new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                        if (msg.what == 0) {
                            String[] times = AppUtil.secToTime(Timetemp);
                            Timetemp--;
                            if (times != null) {
                                timeTextViewList.get(0).setText(times[0]);
                                timeTextViewList.get(1).setText(times[1]);
                                timeTextViewList.get(2).setText(times[2]);
                            }
                        }

                    }
                };
                setViewPager(data.getData().getXscp(), holder);
            }else{
                holder.mLinearTimeGood.setVisibility(View.GONE);
            }
        } else {
            holder.layout_all2.setVisibility(View.VISIBLE);
            holder.layout_all3.setVisibility(View.VISIBLE);
            List<IndexWrapper.Data.CPSLIST> listData = data.getData().getCpslist();
            holder.tv_title.setText(data.getData().getCpslist().get(position - 1).getName());
            holder.tv_intro.setText(data.getData().getCpslist().get(position - 1).getDescription());
            holder.tv_more.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    MainActivity activity = (MainActivity)mActivity;
                    activity.isFromMainFragmentToClassify=true;
                    activity.id = data.getData().getCpslist().get(position - 1).getId();
                    activity.changeFragment(activity.classify);
                }

            });
            String images = data.getData().getCpslist().get(position - 1).getAdpic().getImages();
            if (TextUtils.isEmpty(images)){
                holder.img_big.setVisibility(View.GONE);
            }else{
                AppUtil.showPic(images,holder.img_big);
                holder.img_big.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent;
                        if(data.getData().getCpslist().get(position-1).getAdpic().getType().equals("class")) {
                            intent = new Intent(mActivity, GoodListActivity.class);
                            intent.putExtra("id",data.getData().getCpslist().get(position-1).getAdpic().getValue());
                        }else{
//                        if (AppUtil.need_to_login(mActivity)) {
//                            return;
//                        }
                            intent = new Intent(mActivity, DetailActivity.class);
                            intent.putExtra("id",data.getData().getCpslist().get(position-1).getAdpic().getValue());
                        }
                        mActivity.startActivity(intent);
                    }

                });
            }
            for (int i = 0; i < 6; i++) {
                final List<IndexWrapper.Data.CPSLIST.CP> cpList = listData.get(position - 1).getCp();
                if (i < cpList.size()) {
                    holder.layouts[i].setVisibility(View.VISIBLE);
                    for (int j = 0; j < listData.get(position - 1).getCp().size(); j++) {
                        holder.tvlist.get(j)[0].setText(cpList.get(j).getTitle());
                        holder.tvlist.get(j)[1].setText(cpList.get(j).getShort_title());
                        holder.tvlist.get(j)[2].setText(cpList.get(j).getDiscount());
                        holder.tvlist.get(j)[3].setText("￥" + cpList.get(j).getPrice());
                        holder.tvlist.get(j)[4].setText("/" + cpList.get(j).getUnits());
                        AppUtil.showPic(cpList.get(j).getPic(),holder.imglists[j]);

                        final int finalJ = j;
                        holder.layouts[j].setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                               if(cpList.get(finalJ).getId()!=null){
//                                   if (AppUtil.need_to_login(mActivity)) {
//                                       return;
//                                   }
                                   Intent intent = new Intent(mActivity, DetailActivity.class);
                                   intent.putExtra("id",cpList.get(finalJ).getId());
                                   mActivity.startActivityForResult(intent, RequstCode.GOTOGOODLIST);
                               }
                            }
                        });
                    }
                } else {
                    holder.layouts[i].setVisibility(View.GONE);
                    int j = listData.size() % 2 != 0 ? listData.size():listData.size()-1;
                    Log.e("MainAdapter", "MainAdapter--onBindViewHolder--listData长度"+listData.size());
                    Log.e("j", "onBindViewHolder: " + j);
//                    holder.layouts[i].setVisibility(View.INVISIBLE);
                    if (cpList.size() <= 4 ) {
                        holder.layout_all3.setVisibility(View.GONE);
                        holder.mTvLine3.setVisibility(View.GONE);
                    } if (cpList.size() <= 2) {
                        holder.layout_all2.setVisibility(View.GONE);
                        holder.mTvLine2.setVisibility(View.GONE);
                    }
                }
            }
        }

    }




    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void setViewPager(IndexWrapper.Data.XSCP xscp, MainHolder holder) {
        dotList.clear();
        if(xscp==null||xscp.getList()==null){
            return;
        }
        holder.dot_layout.removeAllViews();
        ImageLoader imageLoader = ImageLoader.getInstance();
        DisplayImageOptions options = AppUtil.getNormalImageOptions();
        LayoutInflater layoutInflater = LayoutInflater.from(mActivity);
        View view = null;
        List<View> viesList = new ArrayList<>();
        currentIndex = 0;
        int a  = xscp.getList().size()/3;
        a = xscp.getList().size()==0?a-1:a;
        for (int i = 0; i <= a; i++) {
            ImageView dot = new ImageView(mActivity);//原点指标
            dot.setImageDrawable(mActivity.getResources().getDrawable(R.drawable.dot_selecter));
            dot.setPadding(5, 0, 5, 0);
            dot.setEnabled(i == 0 ? false : true);
            dotList.add(dot);
            holder.dot_layout.addView(dot);
            view = layoutInflater.inflate(R.layout.item_main_viewpager, null);
            ImageView [] imgs = {(ImageView) view.findViewById(R.id.img_item1),(ImageView) view.findViewById(R.id.img_item2),(ImageView) view.findViewById(R.id.img_item3)};
            TextView [] tvitem1 ={(TextView) view.findViewById(R.id.tv_item1_text1),(TextView) view.findViewById(R.id.tv_item1_text2),(TextView) view.findViewById(R.id.tv_item1_text3),(TextView) view.findViewById(R.id.tv_item1_text4),(TextView) view.findViewById(R.id.tv_item1_text5),(TextView) view.findViewById(R.id.tv_item1_text6)};
            TextView [] tvitem2 ={(TextView) view.findViewById(R.id.tv_item2_text1),(TextView) view.findViewById(R.id.tv_item2_text2),(TextView) view.findViewById(R.id.tv_item2_text3),(TextView) view.findViewById(R.id.tv_item2_text4),(TextView) view.findViewById(R.id.tv_item2_text5),(TextView) view.findViewById(R.id.tv_item2_text6)};
            TextView [] tvitem3 ={(TextView) view.findViewById(R.id.tv_item3_text1),(TextView) view.findViewById(R.id.tv_item3_text2),(TextView) view.findViewById(R.id.tv_item3_text3),(TextView) view.findViewById(R.id.tv_item3_text4),(TextView) view.findViewById(R.id.tv_item3_text5),(TextView) view.findViewById(R.id.tv_item3_text6)};
            List<TextView []> tvlist = new ArrayList<>();
            tvlist.add(tvitem1);
            tvlist.add(tvitem2);
            tvlist.add(tvitem3);
            for (int j = 0; j < 3; j++) {
                if(xscp.getList().size()>i*3+j){
                    final IndexWrapper.Data.XSCP.LIST tempdata = data.getData().getXscp().getList().get(i * 3 + j);
                    AppUtil.showPic(tempdata.getPic(),imgs[j]);
                    tvlist.get(j)[0].setText(tempdata.getTitle());
                    tvlist.get(j)[1].setText("￥"+tempdata.getXprice());
                    tvlist.get(j)[2].setText("/"+tempdata.getUnits());
                    tvlist.get(j)[3].setText("￥"+tempdata.getMarket_price());
                    tvlist.get(j)[3].getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG|Paint.ANTI_ALIAS_FLAG);
                    tvlist.get(j)[4].setText("/"+tempdata.getUnits());
                    tvlist.get(j)[5].setText("还剩"+tempdata.getSurplus()+tempdata.getUnits());
                    tvlist.get(j)[5].setBackground(mActivity.getResources().getDrawable(R.drawable.ic_bk));
                    imgs[j].setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
//                            if (AppUtil.need_to_login(mActivity)) {
//                                return;
//                            }
                          Intent intent = new Intent(mActivity,DetailActivity.class);
                            intent.putExtra("id",tempdata.getId());
                            mActivity.startActivityForResult(intent,RequstCode.GOTOGOODLIST);
                        }
                    });
                }else{
                    break;
                }
            }
            viesList.add(view);
        }
        holder.viewpager.setAdapter(new IndexViewPagerAdapter(viesList));
        holder.viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                if (currentIndex == position) {
                    return;
                }
                Log.i("onPageScrolled", "position: " + position + "     currentIndex:" + currentIndex);
                dotList.get(position).setEnabled(false);
                dotList.get(currentIndex).setEnabled(true);
                currentIndex = position;
            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    public int getItemCount() {
        if (data == null || data.getData() == null || data.getData().getCpslist() == null) {
            return 0;
        }
        return data.getData().getCpslist().size() + 1;
    }

    @Override
    public int getItemViewType(int position) {
        return position;
    }


    //倒计时

    /**
     * 开启倒计时
     */
    private void startRun(final int time, final int i) {
        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                if(tag){
                    return;
                }tag =true;
                while (time > 0) {
                    try {
                        Thread.sleep(1000); // sleep 1000ms
                        Message message = Message.obtain();
                        message.what = i;
                        timeHandler.sendMessage(message);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    public void setData(IndexWrapper response) {
        data = response;
        notifyDataSetChanged();
    }
}
